package mblog.core.persist.service.impl;

import mblog.core.data.PostKeyword;
import mblog.core.persist.dao.PostKeywordDao;
import mblog.core.persist.entity.PostKeywordPO;
import mblog.core.persist.service.PostKeywordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class PostKeywordServiceImpl implements PostKeywordService {

    @Autowired
    private PostKeywordDao postKeywordDao;

    @Override
    public List<PostKeyword> hotKeywords() {
        List<PostKeywordPO> pos = postKeywordDao.hotKeywords();
        List<PostKeyword> pw = new ArrayList<>();
        for (PostKeywordPO po : pos) {
            pw.add(new PostKeyword(po));
        }
        return pw;
    }

    @Override
    public void updateKeyword(String keyword) {
        PostKeywordPO postKeywordPO = postKeywordDao.findByKeyword(keyword);
        if (postKeywordPO != null) {
            postKeywordPO.addAmount(1);
            postKeywordDao.save(postKeywordPO);
            return;
        }
        postKeywordPO = new PostKeywordPO(keyword, 1L);
        postKeywordDao.save(postKeywordPO);
    }
}
